<template>
  <div class="player-bar">
    <!-- 歌曲信息 -->
    <div class="song-info">
      <div class="cover">
        <img
          :src="
            (currentSongData || currentSong)?.coverUrl ||
            (currentSongData || currentSong)?.cover_url ||
            'https://picsum.photos/50/50?random=1'
          "
          alt="专辑封面"
        />
      </div>
      <div class="details">
        <router-link
          :to="{
            name: 'SongDetail',
            params: { id: (currentSongData || currentSong)?.songId || (currentSongData || currentSong)?.song_id || 0 },
          }"
          class="title"
        >
          {{ (currentSongData || currentSong)?.songName || (currentSongData || currentSong)?.song_name || "暂无歌曲" }}
        </router-link>
        <div class="artist">{{ artistName || "未知歌手" }}</div>
      </div>

      <!-- 收藏按钮 -->
      <el-button
        circle
        class="favorite-btn"
        :type="isFavorite ? 'danger' : 'default'"
        @click="toggleFavorite"
      >
        <el-icon :size="18"
          ><StarFilled v-if="isFavorite" /><Star v-else
        /></el-icon>
      </el-button>
    </div>

    <!-- 播放控制 -->
    <div class="controls">
      <el-button circle plain @click="playPrevious">
        <el-icon><CaretLeft /></el-icon>
      </el-button>
      <el-button circle type="primary" class="play-btn" @click="togglePlay">
        <el-icon v-if="isPlaying"><VideoPause /></el-icon>
        <el-icon v-else><VideoPlay /></el-icon>
      </el-button>
      <el-button circle plain @click="playNext">
        <el-icon><CaretRight /></el-icon>
      </el-button>
    </div>

    <!-- 进度条 -->
    <div class="progress-container">
      <span class="time">{{ formatTime(currentTime) }}</span>
      <el-slider
        v-model="progressPercentage"
        :show-tooltip="false"
        class="progress-slider"
        @change="seekPosition"
      />
      <span class="time">{{ formatTime(duration) }}</span>
    </div>

    <!-- 附加控制 -->
    <div class="additional-controls">
      <!-- 音量控制 -->
      <div class="volume-control">
        <el-icon><Headset /></el-icon>
        <el-slider
          v-model="volume"
          :min="0"
          :max="100"
          :show-tooltip="false"
          class="volume-slider"
        />
      </div>

      <!-- 歌单管理按钮 -->
      <el-dropdown trigger="click" @command="handlePlaylistCommand">
        <el-button circle plain>
          <el-icon><FolderOpened /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              v-for="playlist in playlists"
              :key="playlist.playlistId"
              :command="playlist.playlistId"
            >
              {{ playlist.playlistName }}
            </el-dropdown-item>
            <el-dropdown-item divided command="new">
              <el-icon><Plus /></el-icon> 创建新歌单
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <!-- 分享按钮 -->
      <el-button circle plain @click="showShareDialog">
        <el-icon><Share /></el-icon>
      </el-button>
    </div>

    <!-- 创建歌单对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建歌单"
      width="400px"
      append-to-body
      class="centered-create-dialog"
    >
      <el-input v-model="newPlaylistName" placeholder="输入歌单名称" />
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createPlaylist">创建</el-button>
      </template>
    </el-dialog>

    <!-- 分享对话框 -->
    <el-dialog
      v-model="shareDialogVisible"
      title="分享歌曲"
      width="400px"
      append-to-body
      class="centered-share-dialog"
    >
      <div class="share-dialog">
        <div class="share-link-container">
          <div class="share-description">
            <el-icon :size="24" class="link-icon"><Link /></el-icon>
            <p class="share-title">复制以下链接分享给朋友</p>
          </div>
          <el-input v-model="shareLink" readonly class="share-link-input">
            <template #append>
              <el-button type="primary" @click="copyShareLink">
                <el-icon><DocumentCopy /></el-icon> 复制
              </el-button>
            </template>
          </el-input>
          <div class="copy-success" v-if="copySuccess">
            <el-icon color="#67C23A"><CircleCheckFilled /></el-icon>
            <span>链接已复制到剪贴板</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  CaretLeft,
  CaretRight,
  CircleCheckFilled,
  DocumentCopy,
  FolderOpened,
  Headset,
  Link,
  Plus,
  Share,
  Star,
  StarFilled,
  VideoPause,
  VideoPlay,
} from "@element-plus/icons-vue";

import api from "@/services/api.js";
import eventBus, { EventType } from "@/utils/eventBus.js";
import { ElMessage } from "element-plus";

export default {
  name: "PlayerBar",
  components: {
    CaretLeft,
    CaretRight,
    VideoPlay,
    VideoPause,
    FolderOpened,
    Share,
    Star,
    StarFilled,
    Headset,
    Plus,
    Link,
    DocumentCopy,
    CircleCheckFilled,
  },
  props: {
    currentSong: {
      type: Object,
      required: false,
      default: () => null,
    },
    playlist: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      isPlaying: false,
      progressPercentage: 0,
      currentTime: 0,
      duration: 0,
      volume: 70,
      audioPlayer: null,
      isFavorite: false,
      artistName: "",
      playlists: [],
      createDialogVisible: false,
      newPlaylistName: "",
      shareDialogVisible: false,
      shareLink: "",
      copySuccess: false,
      playTokenExpireTime: 0,
      currentPlayUrl: "",
      currentPlayToken: "",
      // 添加内部歌曲数据管理
      currentSongData: null,
      // 添加测试歌曲数据
      testSongs: [
        {
          songId: 1,
          songName: "双截棍",
          artistName: "周杰伦",
          artistId: 1,
          coverUrl: "https://picsum.photos/300/300?random=1",
          file_url: "/public/song/周杰伦-双截棍.mp3",
          duration: 180,
          lyrics: "/public/Lyric/周杰伦-双截棍.lrc"
        },
        {
          songId: 2,
          songName: "就是爱你",
          artistName: "陶喆",
          artistId: 2,
          coverUrl: "https://picsum.photos/300/300?random=2",
          file_url: "/song/陶喆-就是爱你.mp3",
          duration: 240,
          lyrics: "/Lyric/陶喆-就是爱你.lrc"
        }
      ],
      currentSongIndex: 0,
      playlist: []
    };
  },
  computed: {
    // 计算属性
  },
  watch: {
    volume(newVolume) {
      if (this.audioPlayer) {
        this.audioPlayer.volume = newVolume / 100;
      }
    },
    // 监听从外部传入的currentSong变化
    "currentSong.songId"(newSongId, oldSongId) {
      if (newSongId && newSongId !== oldSongId) {
        this.loadSong(this.currentSong);
        if (this.currentSong.artist_id || this.currentSong.artistId) {
          this.fetchArtistName(
            this.currentSong.artist_id || this.currentSong.artistId
          );
        }
      }
    },
    isPlaying(playing) {
      if (this.audioPlayer && this.audioPlayer.src) {
        if (playing) {
          this.audioPlayer.play().catch((error) => {
            console.error("播放失败:", error);
            this.isPlaying = false;
          });
        } else {
          this.audioPlayer.pause();
        }
      }
    },
  },
  async mounted() {
    this.audioPlayer = new Audio();
    this.audioPlayer.volume = this.volume / 100;
    this.audioPlayer.addEventListener("timeupdate", this.updateProgress);
    this.audioPlayer.addEventListener("loadedmetadata", () => {
      this.duration = this.audioPlayer.duration;
    });
    this.audioPlayer.addEventListener("ended", this.playNext);
    this.audioPlayer.addEventListener("error", this.handleAudioError);

    if (this.currentSong) {
      this.loadSong(this.currentSong);
      this.fetchArtistName(this.currentSong.artistId);
    }

    await this.fetchUserPlaylists();

    // 监听来自其他组件的播放歌曲事件
    eventBus.on(EventType.PLAY_SONG, (songData) => {
      if (songData) {
        if (typeof songData === "number" || typeof songData === "string") {
          // 如果只传了 songId
          this.playSongById(songData);
        } else {
          // 如果传了完整歌曲对象
          const song = songData;
          this.currentSong = song;
          this.isPlaying = true;
          this.loadSong(song);
        }
      }
    });
  },
  beforeUnmount() {
    if (this.audioPlayer) {
      this.audioPlayer.pause();
      this.audioPlayer.removeEventListener("timeupdate", this.updateProgress);
      this.audioPlayer.removeEventListener("loadedmetadata", null);
      this.audioPlayer.removeEventListener("ended", this.playNext);
      this.audioPlayer.removeEventListener("error", this.handleAudioError);
      this.audioPlayer = null;
    }

    // 移除事件监听
    eventBus.off(EventType.PLAY_SONG);
  },
  methods: {
    // 加载歌曲
    async loadSong(song) {
      if (!song) return;

      try {
        let audioUrl = '';
        let songInfo = song;

        // 如果没有传入歌曲对象，则使用测试歌曲数据
        if (!song.songId && !song.songName) {
          songInfo = this.testSongs[this.currentSongIndex];
        }

        // 设置音频源
        if (songInfo.file_url) {
          audioUrl = songInfo.file_url;
        } else if (songInfo.fileUrl) {
          audioUrl = songInfo.fileUrl;
        } else {
          // 使用测试数据中的第一首歌
          audioUrl = this.testSongs[0].file_url;
          songInfo = this.testSongs[0];
        }

        // 设置当前歌曲信息到内部数据（不修改prop）
        this.currentSongData = {
          songId: songInfo.songId || songInfo.song_id,
          songName: songInfo.songName || songInfo.song_name,
          artistName: songInfo.artistName || songInfo.artist_name,
          artistId: songInfo.artistId || songInfo.artist_id,
          coverUrl: songInfo.coverUrl || songInfo.cover_url,
          file_url: audioUrl,
          duration: songInfo.duration
        };

        this.artistName = this.currentSongData.artistName || "未知歌手";

        // 设置音频播放器
        this.audioPlayer.src = audioUrl;
        this.audioPlayer.load();

        // 等待音频加载完成
        this.audioPlayer.addEventListener('loadeddata', () => {
          this.duration = this.audioPlayer.duration || songInfo.duration || 0;
          console.log(`歌曲加载完成: ${this.currentSongData.songName}, 时长: ${this.duration}s`);
        }, { once: true });

        // 如果设置了播放状态，则开始播放
        if (this.isPlaying) {
          this.audioPlayer.play().catch((error) => {
            console.error("自动播放失败:", error);
            this.isPlaying = false;
            ElMessage.warning("自动播放失败，请手动点击播放");
          });
        }

        ElMessage.success(`已加载: ${this.currentSongData.songName}`);
      } catch (error) {
        console.error("加载歌曲失败:", error);
        ElMessage.error("加载歌曲失败");
        this.isPlaying = false;
      }
    },

    // 音频错误处理
    handleAudioError(event) {
      const error = this.audioPlayer.error;
      console.error("音频播放错误:", error);

      let errorMessage = "音频播放错误";
      if (error) {
        switch (error.code) {
          case 1:
            errorMessage = "音频播放被中止";
            break;
          case 2:
            errorMessage = "网络错误";
            break;
          case 3:
            errorMessage = "音频解码错误";
            break;
          case 4:
            errorMessage = "音频格式不支持";
            break;
          default:
            errorMessage = "未知播放错误";
        }
      }

      ElMessage.error(errorMessage);
      this.isPlaying = false;
    },

    // 播放/暂停切换
    async togglePlay() {
      try {
        if (!this.audioPlayer.src || !this.currentSong) {
          // 没有歌曲时，加载第一首测试歌曲
          console.log("没有当前歌曲，加载默认歌曲");
          await this.loadSong(this.testSongs[0]);
          this.currentSongIndex = 0;
        }

        if (this.isPlaying) {
          this.audioPlayer.pause();
          this.isPlaying = false;
          console.log("暂停播放");
        } else {
          const playPromise = this.audioPlayer.play();
          if (playPromise !== undefined) {
            await playPromise;
            this.isPlaying = true;
            console.log("开始播放");
          }
        }
      } catch (error) {
        console.error("播放控制失败:", error);
        this.isPlaying = false;
        ElMessage.error("播放失败: " + error.message);
      }
    },

    // 播放上一首
    async playPrevious() {
      if (this.testSongs.length === 0) return;

      this.currentSongIndex = this.currentSongIndex > 0 ?
        this.currentSongIndex - 1 :
        this.testSongs.length - 1;

      const wasPlaying = this.isPlaying;
      await this.loadSong(this.testSongs[this.currentSongIndex]);

      if (wasPlaying) {
        this.isPlaying = true;
        this.audioPlayer.play().catch(console.error);
      }

      ElMessage.info(`上一首: ${this.testSongs[this.currentSongIndex].songName}`);
    },

    // 播放下一首
    async playNext() {
      if (this.testSongs.length === 0) return;

      this.currentSongIndex = this.currentSongIndex < this.testSongs.length - 1 ?
        this.currentSongIndex + 1 :
        0;

      const wasPlaying = this.isPlaying;
      await this.loadSong(this.testSongs[this.currentSongIndex]);

      if (wasPlaying) {
        this.isPlaying = true;
        this.audioPlayer.play().catch(console.error);
      }

      ElMessage.info(`下一首: ${this.testSongs[this.currentSongIndex].songName}`);
    },

    // 播放指定歌曲ID
    async playSongById(songId) {
      try {
        // 在测试歌曲中查找
        const songIndex = this.testSongs.findIndex(song => song.songId == songId);
        if (songIndex !== -1) {
          this.currentSongIndex = songIndex;
          await this.loadSong(this.testSongs[songIndex]);
          this.isPlaying = true;
          this.audioPlayer.play().catch(console.error);
          return;
        }

        // 如果测试歌曲中没有找到，尝试通过API获取
        const response = await api.musicApi.getSongDetail(songId);
        if (response.code === 200) {
          const songData = response.data;
          const formattedSong = {
            songId: songData.song_id || songData.songId,
            songName: songData.song_name || songData.songName,
            artistName: songData.artist_name || songData.artistName,
            artistId: songData.artist_id || songData.artistId,
            file_url: songData.file_url || songData.fileUrl,
            coverUrl: songData.cover_url || songData.coverUrl,
            duration: songData.duration,
          };

          await this.loadSong(formattedSong);
          this.isPlaying = true;
          this.audioPlayer.play().catch(console.error);
        } else {
          throw new Error("歌曲不存在");
        }
      } catch (error) {
        console.error("播放歌曲失败:", error);
        ElMessage.error("播放歌曲失败: " + error.message);
      }
    },

    // 播放测试歌曲（公共方法）
    async playTestSong(index = 0) {
      if (index >= 0 && index < this.testSongs.length) {
        this.currentSongIndex = index;
        await this.loadSong(this.testSongs[index]);
        this.isPlaying = true;
        this.audioPlayer.play().catch((error) => {
          console.error("播放失败:", error);
          this.isPlaying = false;
        });
      }
    },

    // 获取测试歌曲列表
    getTestSongs() {
      return this.testSongs;
    },

    // 获取歌手名称
    async fetchArtistName(artistId) {
      try {
        const response = await api.artistApi.getArtistDetail(artistId);
        if (response.code === 200) {
          this.artistName = response.data.artist_name;
        } else {
          throw new Error("获取歌手信息失败");
        }
      } catch (error) {
        console.error("获取歌手信息出错:", error);
        this.artistName = "未知歌手";
      }
    },

    // 检查收藏状态
    async checkFavoriteStatus(songId) {
      try {
        const response = await api.collectionApi.checkCollectionStatus(
          songId,
          "song"
        );
        if (response.code === 200) {
          this.isFavorite = response.data.isCollected;
        }
      } catch (error) {
        console.error("检查收藏状态失败:", error);
        this.isFavorite = false;
      }
    },

    // 获取用户歌单
    async fetchUserPlaylists() {
      try {
        // 这里应该传入实际的用户ID，可以从store或localStorage获取
        const userId = localStorage.getItem("userId") || 1; // 临时使用默认用户ID
        const response = await api.playlistApi.getUserPlaylists(userId, {
          page: 1,
          size: 20,
        });

        if (response.code === 200) {
          this.playlists = response.data.records.map((item) => ({
            playlistId: item.playlist_id,
            playlistName: item.playlist_name,
          }));
        } else {
          throw new Error("获取歌单失败");
        }
      } catch (error) {
        console.error("获取歌单出错:", error);
        // 使用模拟数据作为备选
        this.playlists = [
          { playlistId: 1, playlistName: "我的最爱" },
          { playlistId: 2, playlistName: "放松音乐" },
          { playlistId: 3, playlistName: "工作专注" },
        ];
      }
    },

    // 更新播放进度
    updateProgress() {
      this.currentTime = this.audioPlayer.currentTime;
      this.progressPercentage = (this.currentTime / this.duration) * 100 || 0;
    },

    // 跳转播放位置
    seekPosition(value) {
      const position = (value / 100) * this.duration;
      this.audioPlayer.currentTime = position;
    },

    // 格式化时间
    formatTime(seconds) {
      if (isNaN(seconds)) return "0:00";
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins}:${secs < 10 ? "0" : ""}${secs}`;
    },

    // 收藏/取消收藏
    async toggleFavorite() {
      if (!this.currentSong || !this.currentSong.songId) {
        ElMessage.warning("没有可收藏的歌曲");
        return;
      }

      try {
        if (this.isFavorite) {
          // 取消收藏
          await api.collectionApi.removeCollection(
            this.currentSong.songId,
            "song"
          );
          this.isFavorite = false;
          ElMessage.success("已取消收藏");
        } else {
          // 添加收藏
          await api.collectionApi.addCollection({
            targetId: this.currentSong.songId,
            targetType: "song",
          });
          this.isFavorite = true;
          ElMessage.success("已添加到收藏");
        }
      } catch (error) {
        console.error("收藏操作失败:", error);
        ElMessage.error("操作失败，请重试");
        // 恢复原状态
        this.isFavorite = !this.isFavorite;
      }
    },

    // 处理歌单命令
    async handlePlaylistCommand(command) {
      if (command === "new") {
        this.createDialogVisible = true;
      } else {
        try {
          const playlist = this.playlists.find((p) => p.playlistId === command);
          if (playlist) {
            await this.addToPlaylist(playlist);
          }
        } catch (error) {
          console.error("添加到歌单失败:", error);
          ElMessage.error("添加到歌单失败");
        }
      }
    },

    // 创建新歌单
    async createPlaylist() {
      if (!this.newPlaylistName.trim()) {
        ElMessage.warning("请输入歌单名称");
        return;
      }

      try {
        const response = await api.playlistApi.createPlaylist({
          playlistName: this.newPlaylistName,
          description: "",
          isPublic: 1,
        });

        if (response.code === 200) {
          const newPlaylist = {
            playlistId: response.data.playlistId,
            playlistName: this.newPlaylistName,
          };

          this.playlists.push(newPlaylist);
          this.newPlaylistName = "";
          this.createDialogVisible = false;

          ElMessage.success(`歌单 "${newPlaylist.playlistName}" 创建成功`);
        } else {
          throw new Error(response.message || "创建失败");
        }
      } catch (error) {
        console.error("创建歌单失败:", error);
        ElMessage.error("创建歌单失败");
      }
    },

    // 添加到歌单
    async addToPlaylist(playlist) {
      if (!this.currentSong || !this.currentSong.songId) {
        ElMessage.warning("没有可添加的歌曲");
        return;
      }

      try {
        await api.playlistApi.addSongsToPlaylist(playlist.playlistId, {
          songIds: [this.currentSong.songId],
        });

        ElMessage.success(
          `"${this.currentSong.songName}" 已添加到 "${playlist.playlistName}"`
        );
      } catch (error) {
        console.error("添加到歌单失败:", error);
        ElMessage.error("添加到歌单失败");
      }
    },

    // 显示分享对话框
    showShareDialog() {
      const song = this.currentSong;
      if (!song || !song.songId || !song.songName) {
        ElMessage.error("当前无可分享的歌曲");
        return;
      }
      this.shareLink = `https://music.example.com/share/${song.songId}`;
      this.shareDialogVisible = true;
    },

    // 复制分享链接
    copyShareLink() {
      navigator.clipboard
        .writeText(this.shareLink)
        .then(() => {
          this.copySuccess = true;
          setTimeout(() => {
            this.copySuccess = false;
          }, 3000);
        })
        .catch((err) => {
          console.error("复制失败:", err);
          ElMessage.error("复制链接失败");
        });
    },

    // ========== 公共方法，供外部调用 ==========

    // 播放指定歌曲
    async playSongById(songId) {
      try {
        // 保存最后播放的歌曲ID到本地存储
        localStorage.setItem("lastPlayedSongId", songId);

        const response = await api.musicApi.getSongDetail(songId);
        if (response.code === 200) {
          const songData = response.data;
          // 转换数据格式以兼容组件
          const formattedSong = {
            songId: songData.song_id,
            songName: songData.song_name,
            artistId: songData.artist_id,
            albumId: songData.album_id,
            file_url: songData.file_url,
            cover_url: songData.cover_url || songData.coverUrl,
            duration: songData.duration,
          };

          this.currentSong = formattedSong;
          this.isPlaying = true;
          await this.loadSong(formattedSong);
        } else {
          throw new Error("歌曲不存在");
        }
      } catch (error) {
        console.error("播放歌曲失败:", error);
        ElMessage.error("播放歌曲失败");
      }
    },

    // 设置播放列表
    setPlaylist(playlist) {
      this.playlist = playlist;
    },

    // 获取当前播放状态
    getPlayStatus() {
      return {
        isPlaying: this.isPlaying,
        currentSong: this.currentSong,
        currentTime: this.currentTime,
        duration: this.duration,
        volume: this.volume,
      };
    },
  },
};
</script>

<style scoped>
.player-bar {
  display: flex;
  align-items: center;
  height: 70px;
  padding: 0 20px;
  gap: 20px;
  background: white;
  border-top: 1px solid #eee;
  box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.song-info {
  display: flex;
  align-items: center;
  min-width: 200px;
  position: relative;
}

.cover img {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 12px;
}

.details {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.title {
  font-weight: 600;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #333;
  text-decoration: none;
  transition: color 0.2s;
  cursor: pointer;
}

.title:hover {
  color: #6b46c1;
}

.artist {
  font-size: 12px;
  color: #888;
}

.favorite-btn {
  margin-left: 10px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.play-btn {
  width: 40px;
  height: 40px;
}

.progress-container {
  flex: 1;
  display: flex;
  align-items: center;
  max-width: 500px;
  gap: 10px;
}

.time {
  font-size: 12px;
  color: #999;
  min-width: 40px;
}

.progress-slider {
  flex: 1;
}

:deep(.progress-slider .el-slider__runway) {
  height: 4px;
  background-color: #e4e7eb;
  margin: 0;
}

:deep(.progress-slider .el-slider__bar) {
  height: 4px;
  background: linear-gradient(90deg, #acb3d8, #846fd4);
}

:deep(.progress-slider .el-slider__button) {
  width: 12px;
  height: 12px;
  border: 2px solid #7986c6;
}

.additional-controls {
  display: flex;
  align-items: center;
  gap: 15px;
  min-width: 180px;
}

.volume-control {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 120px;
}

.volume-slider {
  flex: 1;
}

:deep(.volume-slider .el-slider__runway) {
  height: 4px;
  background-color: #e4e7eb;
  margin: 0;
}

:deep(.volume-slider .el-slider__bar) {
  height: 4px;
  background: #a0a0a0;
}

:deep(.volume-slider .el-slider__button) {
  width: 10px;
  height: 10px;
  border: 2px solid #7986c6;
}
</style>
